package org.practice.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadFileServlet extends HttpServlet {

	private static final long serialVersionUID = -6117485644446728733L;
	/*web应用启动的时候初始化，只初始化一次，以后就可以处理相关请求*/
	@Override
	public void init() throws ServletException {
		System.out.println("==========初始化DownloadFileServlet========");
		super.init();
	}
	
	/*servlet调用service方法或者doGet方法来处理相关请求*/
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		System.out.println("==========开始调用DownloadFileServlet service方法============");
		//get请求获取参数乱码:new String(regDept.getBytes("ISO8859-1"),"UTF-8");或配置tomcat server.xml 
		String chineseName=request.getParameter("fileName");
		String filePathName = request.getSession().getServletContext().getRealPath("\\temp")+"\\"+chineseName;
		
		//下载文件名带中文乱码，解决办法
		String downloadName = java.net.URLEncoder.encode(chineseName, "UTF-8");
		if (downloadName.length() > 150) {//当大于150个字节时，上面的办法不行,超出浏览器的限制
			//根据request的locale得出可能的编码，中文操作系统通常是gb2312
			downloadName = new String(chineseName.getBytes("gb2312"), "ISO8859-1");
		}
		response.setHeader("Content-Type","application/octet-stream");
		//当在网络中传输时，setHeader方法中的字符只能按ISO8859-1传输
		response.setHeader("Content-Disposition", "attachment; filename=" + downloadName);
		
		File file=new File(filePathName);
		OutputStream outputStream = response.getOutputStream();
		InputStream inputStream=new FileInputStream(file);
		byte[] buffer = new byte[1024];
		int i = -1;
		while ((i = inputStream.read(buffer)) != -1) {
			 outputStream.write(buffer, 0, i);
		}
		outputStream.flush();
		if(inputStream != null){
			inputStream.close();
		}
		if(outputStream != null){
			outputStream.close();
		}
		System.out.println("delete file");
		file.delete();
	}
   
   /*web应用停止或重新部署的时候才销毁，*/
   @Override
	public void destroy() {
	   System.out.println("============销毁DownloadFileServlet===========");
	   super.destroy();
	}
}
